// 导入导出页面

// 加载导入导出页面
function loadImportExportPage(container) {
    container.innerHTML = `
        ${createPageTitle('导入导出', 'fas fa-exchange-alt')}
        
        <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
            <!-- 导入区域 -->
            <div class="card bg-base-100 shadow-xl">
                <div class="card-body">
                    <h2 class="card-title">
                        <i class="fas fa-upload text-primary"></i>
                        数据导入
                    </h2>
                    
                    <div class="space-y-4">
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text">选择数据类型</span>
                            </label>
                            <select id="import-type" class="select select-bordered">
                                <option value="work-plan">工作进度计划</option>
                                <option value="outsource">外发清单</option>
                                <option value="steel-mesh">钢网追踪</option>
                                <option value="fixture">治具追踪</option>
                                <option value="sop">SOP签核追踪</option>
                                <option value="data-query">数据查询</option>
                            </select>
                        </div>
                        
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text">选择JSON文件</span>
                            </label>
                            <input type="file" id="import-file" class="file-input file-input-bordered" accept=".json">
                        </div>
                        
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i>
                            <span>支持拖拽上传，文件格式必须为JSON</span>
                        </div>
                        
                        <button class="btn btn-primary w-full" onclick="handleImport()">
                            <i class="fas fa-upload mr-2"></i>开始导入
                        </button>
                    </div>
                    
                    <div id="import-result" class="mt-4"></div>
                </div>
            </div>
            
            <!-- 导出区域 -->
            <div class="card bg-base-100 shadow-xl">
                <div class="card-body">
                    <h2 class="card-title">
                        <i class="fas fa-download text-success"></i>
                        数据导出
                    </h2>
                    
                    <div class="space-y-4">
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text">选择数据类型</span>
                            </label>
                            <select id="export-type" class="select select-bordered">
                                <option value="work-plan">工作进度计划</option>
                                <option value="outsource">外发清单</option>
                                <option value="steel-mesh">钢网追踪</option>
                                <option value="fixture">治具追踪</option>
                                <option value="sop">SOP签核追踪</option>
                                <option value="data-query">数据查询</option>
                            </select>
                        </div>
                        
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text">导出格式</span>
                            </label>
                            <div class="btn-group w-full">
                                <button class="btn btn-outline btn-sm" onclick="setExportFormat('json')">
                                    <i class="fas fa-file-code mr-1"></i>JSON
                                </button>
                                <button class="btn btn-outline btn-sm" onclick="setExportFormat('csv')">
                                    <i class="fas fa-file-csv mr-1"></i>CSV
                                </button>
                                <button class="btn btn-outline btn-sm" onclick="setExportFormat('excel')">
                                    <i class="fas fa-file-excel mr-1"></i>Excel
                                </button>
                            </div>
                        </div>
                        
                        <div class="form-control">
                            <label class="label">
                                <span class="label-text">导出选项</span>
                            </label>
                            <div class="space-y-2">
                                <label class="label cursor-pointer">
                                    <span class="label-text">包含历史数据</span>
                                    <input type="checkbox" id="include-history" class="checkbox checkbox-primary">
                                </label>
                                <label class="label cursor-pointer">
                                    <span class="label-text">仅导出延期项目</span>
                                    <input type="checkbox" id="only-overdue" class="checkbox checkbox-warning">
                                </label>
                            </div>
                        </div>
                        
                        <button class="btn btn-success w-full" onclick="handleExport()">
                            <i class="fas fa-download mr-2"></i>开始导出
                        </button>
                    </div>
                    
                    <div id="export-result" class="mt-4"></div>
                </div>
            </div>
        </div>
        
        <!-- 数据预览区域 -->
        <div class="card bg-base-100 shadow-xl mt-6">
            <div class="card-body">
                <h2 class="card-title">
                    <i class="fas fa-eye text-info"></i>
                    数据预览
                </h2>
                
                <div class="form-control">
                    <label class="label">
                        <span class="label-text">选择数据类型预览</span>
                    </label>
                    <select id="preview-type" class="select select-bordered" onchange="loadDataPreview()">
                        <option value="">请选择数据类型</option>
                        <option value="work-plan">工作进度计划</option>
                        <option value="outsource">外发清单</option>
                        <option value="steel-mesh">钢网追踪</option>
                        <option value="fixture">治具追踪</option>
                        <option value="sop">SOP签核追踪</option>
                        <option value="data-query">数据查询</option>
                    </select>
                </div>
                
                <div id="data-preview" class="mt-4">
                    <div class="text-center text-gray-500 py-8">
                        <i class="fas fa-database text-4xl mb-2"></i>
                        <p>请选择数据类型进行预览</p>
                    </div>
                </div>
            </div>
        </div>
    `;
    
    // 绑定拖拽上传事件
    bindDragDropEvents();
}

// 绑定拖拽上传事件
function bindDragDropEvents() {
    const container = document.querySelector('#import-export-page');
    if (!container) return;
    
    container.addEventListener('dragover', (e) => {
        e.preventDefault();
        e.stopPropagation();
    });
    
    container.addEventListener('drop', (e) => {
        e.preventDefault();
        e.stopPropagation();
        
        const files = e.dataTransfer.files;
        if (files.length > 0 && files[0].name.endsWith('.json')) {
            document.getElementById('import-file').files = files;
            showSuccess('文件已选择：' + files[0].name);
        }
    });
}

// 设置导出格式
let currentExportFormat = 'json';
function setExportFormat(format) {
    currentExportFormat = format;
    
    // 更新按钮状态
    const buttons = document.querySelectorAll('.btn-group .btn');
    buttons.forEach(btn => btn.classList.remove('btn-active'));
    
    const activeBtn = Array.from(buttons).find(btn => 
        btn.textContent.toLowerCase().includes(format)
    );
    if (activeBtn) {
        activeBtn.classList.add('btn-active');
    }
}

// 处理导入
async function handleImport() {
    const fileInput = document.getElementById('import-file');
    const dataType = document.getElementById('import-type').value;
    
    if (!fileInput.files.length) {
        showWarning('请选择要导入的文件');
        return;
    }
    
    if (!dataType) {
        showWarning('请选择数据类型');
        return;
    }
    
    const file = fileInput.files[0];
    
    try {
        const text = await file.text();
        const data = JSON.parse(text);
        
        // 验证数据格式
        if (!Array.isArray(data)) {
            throw new Error('数据格式错误：必须是数组格式');
        }
        
        // 根据数据类型调用相应的API
        const result = await importData(dataType, data);
        
        showImportResult(result, dataType);
        
    } catch (error) {
        showError('导入失败：' + error.message);
    }
}

// 导入数据
async function importData(dataType, data) {
    const apiMap = {
        'work-plan': workPlanAPI,
        'outsource': outsourceAPI,
        'steel-mesh': steelMeshAPI,
        'fixture': fixtureAPI,
        'sop': sopAPI,
        'data-query': dataQueryAPI
    };
    
    const api = apiMap[dataType];
    if (!api) {
        throw new Error('不支持的数据类型');
    }
    
    let successCount = 0;
    let errorCount = 0;
    const errors = [];
    
    // 批量导入数据
    for (let i = 0; i < data.length; i++) {
        try {
            await api.create(data[i]);
            successCount++;
        } catch (error) {
            errorCount++;
            errors.push({
                index: i,
                data: data[i],
                error: error.message
            });
        }
    }
    
    return {
        total: data.length,
        success: successCount,
        error: errorCount,
        errors: errors
    };
}

// 显示导入结果
function showImportResult(result, dataType) {
    const resultDiv = document.getElementById('import-result');
    const typeNames = {
        'work-plan': '工作进度计划',
        'outsource': '外发清单',
        'steel-mesh': '钢网追踪',
        'fixture': '治具追踪',
        'sop': 'SOP签核追踪',
        'data-query': '数据查询'
    };
    
    const typeName = typeNames[dataType] || dataType;
    
    let html = `
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i>
            <div>
                <h3 class="font-bold">导入完成</h3>
                <div class="text-sm">
                    数据类型：${typeName}<br>
                    总计：${result.total} 条<br>
                    成功：${result.success} 条<br>
                    失败：${result.error} 条
                </div>
            </div>
        </div>
    `;
    
    if (result.errors.length > 0) {
        html += `
            <div class="alert alert-warning mt-2">
                <i class="fas fa-exclamation-triangle"></i>
                <div>
                    <h3 class="font-bold">失败记录</h3>
                    <div class="text-sm">
                        ${result.errors.slice(0, 5).map(err => 
                            `第${err.index + 1}条：${err.error}`
                        ).join('<br>')}
                        ${result.errors.length > 5 ? `<br>... 还有 ${result.errors.length - 5} 条失败记录` : ''}
                    </div>
                </div>
            </div>
        `;
    }
    
    resultDiv.innerHTML = html;
}

// 处理导出
async function handleExport() {
    const dataType = document.getElementById('export-type').value;
    const includeHistory = document.getElementById('include-history').checked;
    const onlyOverdue = document.getElementById('only-overdue').checked;
    
    if (!dataType) {
        showWarning('请选择数据类型');
        return;
    }
    
    try {
        const data = await getExportData(dataType, includeHistory, onlyOverdue);
        
        if (data.length === 0) {
            showWarning('没有数据可导出');
            return;
        }
        
        // 根据格式导出
        if (currentExportFormat === 'json') {
            exportToJSON(data, `${dataType}_${formatDate(new Date(), 'YYYY-MM-DD')}.json`);
        } else if (currentExportFormat === 'csv') {
            const csvData = convertToCSVFormat(data, dataType);
            exportToCSV(csvData, `${dataType}_${formatDate(new Date(), 'YYYY-MM-DD')}.csv`);
        } else if (currentExportFormat === 'excel') {
            // Excel导出使用CSV格式，用户可以在Excel中打开
            const csvData = convertToCSVFormat(data, dataType);
            exportToCSV(csvData, `${dataType}_${formatDate(new Date(), 'YYYY-MM-DD')}.csv`);
        }
        
        showExportResult(data.length, dataType);
        
    } catch (error) {
        showError('导出失败：' + error.message);
    }
}

// 获取导出数据
async function getExportData(dataType, includeHistory, onlyOverdue) {
    const apiMap = {
        'work-plan': workPlanAPI,
        'outsource': outsourceAPI,
        'steel-mesh': steelMeshAPI,
        'fixture': fixtureAPI,
        'sop': sopAPI,
        'data-query': dataQueryAPI
    };
    
    const api = apiMap[dataType];
    if (!api) {
        throw new Error('不支持的数据类型');
    }
    
    let data = await api.getAll();
    
    // 如果只导出延期项目
    if (onlyOverdue) {
        if (api.getOverdue) {
            data = await api.getOverdue();
        } else {
            // 手动过滤延期项目
            data = data.filter(item => {
                const expectedDate = item.expectedDate || item.expectedApprovalDate || item.expectedReturnDate;
                const actualDate = item.actualDate || item.actualApprovalDate || item.actualReturnDate;
                return calculateOverdueDays(expectedDate, actualDate) > 0;
            });
        }
    }
    
    return data;
}

// 转换为CSV格式
function convertToCSVFormat(data, dataType) {
    if (!data || data.length === 0) return [];
    
    // 根据数据类型定义CSV列
    const csvColumns = {
        'work-plan': [
            { key: 'workOrder', title: '工单号' },
            { key: 'model', title: '机型' },
            { key: 'quantity', title: '数量' },
            { key: 'plannedDate', title: '计划日期' },
            { key: 'actualDate', title: '实际日期' },
            { key: 'status', title: '状态' },
            { key: 'remark', title: '备注' }
        ],
        'outsource': [
            { key: 'sequence', title: '序号' },
            { key: 'model', title: '机型' },
            { key: 'name', title: '名称' },
            { key: 'quantity', title: '数量' },
            { key: 'supplier', title: '外发厂商' },
            { key: 'outsourceDate', title: '外发日期' },
            { key: 'expectedReturnDate', title: '预计返回日期' },
            { key: 'actualReturnDate', title: '实际返回日期' },
            { key: 'status', title: '状态' },
            { key: 'location', title: '位置' },
            { key: 'remark', title: '备注' }
        ],
        'steel-mesh': [
            { key: 'meshNumber', title: '钢网编号' },
            { key: 'model', title: '机型' },
            { key: 'workOrder', title: '工单号' },
            { key: 'status', title: '状态' },
            { key: 'startDate', title: '开始日期' },
            { key: 'expectedDate', title: '预计完成日期' },
            { key: 'actualDate', title: '实际完成日期' },
            { key: 'remark', title: '备注' }
        ],
        'fixture': [
            { key: 'fixtureNumber', title: '治具编号' },
            { key: 'fixtureType', title: '治具类型' },
            { key: 'model', title: '机型' },
            { key: 'workOrder', title: '工单号' },
            { key: 'status', title: '状态' },
            { key: 'startDate', title: '开始日期' },
            { key: 'expectedDate', title: '预计完成日期' },
            { key: 'actualDate', title: '实际完成日期' },
            { key: 'remark', title: '备注' }
        ],
        'sop': [
            { key: 'sopNumber', title: 'SOP编号' },
            { key: 'sopName', title: 'SOP名称' },
            { key: 'model', title: '机型' },
            { key: 'workOrder', title: '工单号' },
            { key: 'version', title: '版本' },
            { key: 'approvalStatus', title: '签核状态' },
            { key: 'submitDate', title: '提交日期' },
            { key: 'expectedApprovalDate', title: '预计签核日期' },
            { key: 'actualApprovalDate', title: '实际签核日期' },
            { key: 'approver', title: '签核人' },
            { key: 'remark', title: '备注' }
        ],
        'data-query': [
            { key: 'workOrder', title: '工单号' },
            { key: 'model', title: '机型' },
            { key: 'steelMeshStatus', title: '钢网状态' },
            { key: 'fixtureStatus', title: '治具状态' },
            { key: 'bomStatus', title: 'BOM状态' },
            { key: 'sopStatus', title: 'SOP状态' },
            { key: 'remark', title: '备注' }
        ]
    };
    
    const columns = csvColumns[dataType] || Object.keys(data[0]).map(key => ({ key, title: key }));
    
    // 转换数据
    return data.map(item => {
        const row = {};
        columns.forEach(col => {
            row[col.title] = item[col.key] || '';
        });
        return row;
    });
}

// 显示导出结果
function showExportResult(count, dataType) {
    const resultDiv = document.getElementById('export-result');
    const typeNames = {
        'work-plan': '工作进度计划',
        'outsource': '外发清单',
        'steel-mesh': '钢网追踪',
        'fixture': '治具追踪',
        'sop': 'SOP签核追踪',
        'data-query': '数据查询'
    };
    
    const typeName = typeNames[dataType] || dataType;
    
    resultDiv.innerHTML = `
        <div class="alert alert-success">
            <i class="fas fa-check-circle"></i>
            <div>
                <h3 class="font-bold">导出成功</h3>
                <div class="text-sm">
                    数据类型：${typeName}<br>
                    格式：${currentExportFormat.toUpperCase()}<br>
                    数量：${count} 条
                </div>
            </div>
        </div>
    `;
}

// 加载数据预览
async function loadDataPreview() {
    const previewType = document.getElementById('preview-type').value;
    const previewDiv = document.getElementById('data-preview');
    
    if (!previewType) {
        previewDiv.innerHTML = `
            <div class="text-center text-gray-500 py-8">
                <i class="fas fa-database text-4xl mb-2"></i>
                <p>请选择数据类型进行预览</p>
            </div>
        `;
        return;
    }
    
    try {
        const data = await getExportData(previewType, false, false);
        
        if (data.length === 0) {
            previewDiv.innerHTML = `
                <div class="text-center text-gray-500 py-8">
                    <i class="fas fa-inbox text-4xl mb-2"></i>
                    <p>暂无数据</p>
                </div>
            `;
            return;
        }
        
        // 显示数据预览表格
        const previewData = data.slice(0, 10); // 只显示前10条
        const headers = Object.keys(previewData[0]);
        
        previewDiv.innerHTML = `
            <div class="overflow-x-auto">
                <table class="table table-sm">
                    <thead>
                        <tr>
                            ${headers.map(header => `<th>${header}</th>`).join('')}
                        </tr>
                    </thead>
                    <tbody>
                        ${previewData.map(row => `
                            <tr>
                                ${headers.map(header => `<td>${row[header] || '-'}</td>`).join('')}
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            </div>
            <div class="text-sm text-gray-500 mt-2">
                显示前 ${previewData.length} 条记录，总计 ${data.length} 条
            </div>
        `;
        
    } catch (error) {
        previewDiv.innerHTML = `
            <div class="alert alert-error">
                <i class="fas fa-exclamation-circle"></i>
                <span>加载预览失败：${error.message}</span>
            </div>
        `;
    }
}

// 绑定到全局作用域
window.loadImportExportPage = loadImportExportPage;
window.setExportFormat = setExportFormat;
window.handleImport = handleImport;
window.handleExport = handleExport;
window.loadDataPreview = loadDataPreview;
